3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
19 * @ingroup Maintenance
20 * @defgroup Maintenance Maintenance
23 // Bail on old versions of PHP, or if composer has not been run yet to install
25 require_once __DIR__
. '/../includes/PHPVersionCheck.php';
26 wfEntryPointCheck( 'text' );
28 use MediaWiki\Shell\Shell
;
31 * @defgroup MaintenanceArchive Maintenance archives
32 * @ingroup Maintenance
35 // Define this so scripts can easily find doMaintenance.php
36 define( 'RUN_MAINTENANCE_IF_MAIN', __DIR__
. '/doMaintenance.php' );
39 * @deprecated since 1.31
41 define( 'DO_MAINTENANCE', RUN_MAINTENANCE_IF_MAIN
); // original name, harmless
45 use Wikimedia\Rdbms\IDatabase
;
46 use MediaWiki\Logger\LoggerFactory
;
47 use MediaWiki\MediaWikiServices
;
48 use Wikimedia\Rdbms\LBFactory
;
49 use Wikimedia\Rdbms\IMaintainableDatabase
;
52 * Abstract maintenance class for quickly writing and churning out
53 * maintenance scripts with minimal effort. All that _must_ be defined
54 * is the execute() method. See docs/maintenance.txt for more info
55 * and a quick demo of how to use it.
58 * params: registry of named values that may be passed to the script
59 * arg list: registry of positional values that may be passed to the script
60 * options: passed param values
61 * args: passed positional values
64 * mwscript somescript.php --foo=bar baz
66 * bar is the option value of the option for param foo
67 * baz is the arg value at index 0 in the arg list
70 * @ingroup Maintenance
72 abstract class Maintenance
{
74 * Constants for DB access type
75 * @see Maintenance::getDbType()
81 // Const for getStdin()
82 const STDIN_ALL
= 'all';
84 // Array of desired/allowed params
85 protected $mParams = [];
87 // Array of mapping short parameters to long ones
88 protected $mShortParamsMap = [];
90 // Array of desired/allowed args
91 protected $mArgList = [];
93 // This is the list of options that were actually passed
94 protected $mOptions = [];
96 // This is the list of arguments that were actually passed
97 protected $mArgs = [];
99 // Allow arbitrary options to be passed, or only specified ones?
100 protected $mAllowUnregisteredOptions = false;
102 // Name of the script currently running
105 // Special vars for params that are always used
106 protected $mQuiet = false;
107 protected $mDbUser, $mDbPass;
109 // A description of the script, children should change this via addDescription()
110 protected $mDescription = '';
112 // Have we already loaded our user input?
113 protected $mInputLoaded = false;
116 * Batch size. If a script supports this, they should set
117 * a default with setBatchSize()
121 protected $mBatchSize = null;
123 // Generic options added by addDefaultParams()
124 private $mGenericParameters = [];
125 // Generic options which might or not be supported by the script
126 private $mDependantParameters = [];
129 * Used by getDB() / setDB()
130 * @var IMaintainableDatabase
134 /** @var float UNIX timestamp */
135 private $lastReplicationWait = 0.0;
138 * Used when creating separate schema files.
144 * Accessible via getConfig()
151 * @see Maintenance::requireExtension
154 private $requiredExtensions = [];
157 * Used to read the options in the order they were passed.
158 * Useful for option chaining (Ex. dumpBackup.php). It will
159 * be an empty array if the options are passed in through
160 * loadParamsAndArgs( $self, $opts, $args ).
162 * This is an array of arrays where
163 * 0 => the option and 1 => parameter value.
167 public $orderedOptions = [];
170 * Default constructor. Children should call this *first* if implementing
171 * their own constructors
173 public function __construct() {
174 // Setup $IP, using MW_INSTALL_PATH if it exists
176 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
177 ?
getenv( 'MW_INSTALL_PATH' )
178 : realpath( __DIR__
. '/..' );
180 $this->addDefaultParams();
181 register_shutdown_function( [ $this, 'outputChanneled' ], false );
185 * Should we execute the maintenance script, or just allow it to be included
186 * as a standalone class? It checks that the call stack only includes this
187 * function and "requires" (meaning was called from the file scope)
191 public static function shouldExecute() {
192 global $wgCommandLineMode;
194 if ( !function_exists( 'debug_backtrace' ) ) {
195 // If someone has a better idea...
196 return $wgCommandLineMode;
199 $bt = debug_backtrace();
200 $count = count( $bt );
202 return false; // sanity
204 if ( $bt[0]['class'] !== self
::class ||
$bt[0]['function'] !== 'shouldExecute' ) {
205 return false; // last call should be to this function
207 $includeFuncs = [ 'require_once', 'require', 'include', 'include_once' ];
208 for ( $i = 1; $i < $count; $i++
) {
209 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
210 return false; // previous calls should all be "requires"
218 * Do the actual work. All child classes will need to implement this
220 * @return bool|null|void True for success, false for failure. Not returning
221 * a value, or returning null, is also interpreted as success. Returning
222 * false for failure will cause doMaintenance.php to exit the process
223 * with a non-zero exit status.
225 abstract public function execute();
228 * Checks to see if a particular option in supported. Normally this means it
229 * has been registered by the script via addOption.
230 * @param string $name The name of the option
231 * @return bool true if the option exists, false otherwise
233 protected function supportsOption( $name ) {
234 return isset( $this->mParams
[$name] );
238 * Add a parameter to the script. Will be displayed on --help
239 * with the associated description
241 * @param string $name The name of the param (help, version, etc)
242 * @param string $description The description of the param to show on --help
243 * @param bool $required Is the param required?
244 * @param bool $withArg Is an argument required with this option?
245 * @param string|bool $shortName Character to use as short name
246 * @param bool $multiOccurrence Can this option be passed multiple times?
248 protected function addOption( $name, $description, $required = false,
249 $withArg = false, $shortName = false, $multiOccurrence = false
251 $this->mParams
[$name] = [
252 'desc' => $description,
253 'require' => $required,
254 'withArg' => $withArg,
255 'shortName' => $shortName,
256 'multiOccurrence' => $multiOccurrence
259 if ( $shortName !== false ) {
260 $this->mShortParamsMap
[$shortName] = $name;
265 * Checks to see if a particular option exists.
266 * @param string $name The name of the option
269 protected function hasOption( $name ) {
270 return isset( $this->mOptions
[$name] );
274 * Get an option, or return the default.
276 * If the option was added to support multiple occurrences,
277 * this will return an array.
279 * @param string $name The name of the param
280 * @param mixed|null $default Anything you want, default null
283 protected function getOption( $name, $default = null ) {
284 if ( $this->hasOption( $name ) ) {
285 return $this->mOptions
[$name];
287 // Set it so we don't have to provide the default again
288 $this->mOptions
[$name] = $default;
290 return $this->mOptions
[$name];
295 * Add some args that are needed
296 * @param string $arg Name of the arg, like 'start'
297 * @param string $description Short description of the arg
298 * @param bool $required Is this required?
300 protected function addArg( $arg, $description, $required = true ) {
301 $this->mArgList
[] = [
303 'desc' => $description,
304 'require' => $required
309 * Remove an option. Useful for removing options that won't be used in your script.
310 * @param string $name The option to remove.
312 protected function deleteOption( $name ) {
313 unset( $this->mParams
[$name] );
317 * Sets whether to allow unregistered options, which are options passed to
318 * a script that do not match an expected parameter.
319 * @param bool $allow Should we allow?
321 protected function setAllowUnregisteredOptions( $allow ) {
322 $this->mAllowUnregisteredOptions
= $allow;
326 * Set the description text.
327 * @param string $text The text of the description
329 protected function addDescription( $text ) {
330 $this->mDescription
= $text;
334 * Does a given argument exist?
335 * @param int $argId The integer value (from zero) for the arg
338 protected function hasArg( $argId = 0 ) {
339 return isset( $this->mArgs
[$argId] );
344 * @param int $argId The integer value (from zero) for the arg
345 * @param mixed|null $default The default if it doesn't exist
348 protected function getArg( $argId = 0, $default = null ) {
349 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
359 protected function getBatchSize() {
360 return $this->mBatchSize
;
364 * Set the batch size.
365 * @param int $s The number of operations to do in a batch
367 protected function setBatchSize( $s = 0 ) {
368 $this->mBatchSize
= $s;
370 // If we support $mBatchSize, show the option.
371 // Used to be in addDefaultParams, but in order for that to
372 // work, subclasses would have to call this function in the constructor
373 // before they called parent::__construct which is just weird
374 // (and really wasn't done).
375 if ( $this->mBatchSize
) {
376 $this->addOption( 'batch-size', 'Run this many operations ' .
377 'per batch, default: ' . $this->mBatchSize
, false, true );
378 if ( isset( $this->mParams
['batch-size'] ) ) {
379 // This seems a little ugly...
380 $this->mDependantParameters
['batch-size'] = $this->mParams
['batch-size'];
386 * Get the script's name
389 public function getName() {
394 * Return input from stdin.
395 * @param int|null $len The number of bytes to read. If null, just return the handle.
396 * Maintenance::STDIN_ALL returns the full length
399 protected function getStdin( $len = null ) {
400 if ( $len == self
::STDIN_ALL
) {
401 return file_get_contents( 'php://stdin' );
403 $f = fopen( 'php://stdin', 'rt' );
407 $input = fgets( $f, $len );
410 return rtrim( $input );
416 public function isQuiet() {
417 return $this->mQuiet
;
421 * Throw some output to the user. Scripts can call this with no fears,
422 * as we handle all --quiet stuff here
423 * @param string $out The text to show to the user
424 * @param mixed|null $channel Unique identifier for the channel. See function outputChanneled.
426 protected function output( $out, $channel = null ) {
427 // This is sometimes called very early, before Setup.php is included.
428 if ( class_exists( MediaWikiServices
::class ) ) {
429 // Try to periodically flush buffered metrics to avoid OOMs
430 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
431 if ( $stats->getDataCount() > 1000 ) {
432 MediaWiki
::emitBufferedStatsdData( $stats, $this->getConfig() );
436 if ( $this->mQuiet
) {
439 if ( $channel === null ) {
440 $this->cleanupChanneled();
443 $out = preg_replace( '/\n\z/', '', $out );
444 $this->outputChanneled( $out, $channel );
449 * Throw an error to the user. Doesn't respect --quiet, so don't use
450 * this for non-error output
451 * @param string $err The error to display
452 * @param int $die Deprecated since 1.31, use Maintenance::fatalError() instead
454 protected function error( $err, $die = 0 ) {
455 if ( intval( $die ) !== 0 ) {
456 wfDeprecated( __METHOD__
. '( $err, $die )', '1.31' );
457 $this->fatalError( $err, intval( $die ) );
459 $this->outputChanneled( false );
461 ( PHP_SAPI
== 'cli' || PHP_SAPI
== 'phpdbg' ) &&
462 !defined( 'MW_PHPUNIT_TEST' )
464 fwrite( STDERR
, $err . "\n" );
471 * Output a message and terminate the current script.
473 * @param string $msg Error message
474 * @param int $exitCode PHP exit status. Should be in range 1-254.
477 protected function fatalError( $msg, $exitCode = 1 ) {
478 $this->error( $msg );
482 private $atLineStart = true;
483 private $lastChannel = null;
486 * Clean up channeled output. Output a newline if necessary.
488 public function cleanupChanneled() {
489 if ( !$this->atLineStart
) {
491 $this->atLineStart
= true;
496 * Message outputter with channeled message support. Messages on the
497 * same channel are concatenated, but any intervening messages in another
498 * channel start a new line.
499 * @param string $msg The message without trailing newline
500 * @param string|null $channel Channel identifier or null for no
501 * channel. Channel comparison uses ===.
503 public function outputChanneled( $msg, $channel = null ) {
504 if ( $msg === false ) {
505 $this->cleanupChanneled();
510 // End the current line if necessary
511 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
517 $this->atLineStart
= false;
518 if ( $channel === null ) {
519 // For unchanneled messages, output trailing newline immediately
521 $this->atLineStart
= true;
523 $this->lastChannel
= $channel;
527 * Does the script need different DB access? By default, we give Maintenance
528 * scripts normal rights to the DB. Sometimes, a script needs admin rights
529 * access for a reason and sometimes they want no access. Subclasses should
530 * override and return one of the following values, as needed:
531 * Maintenance::DB_NONE - For no DB access at all
532 * Maintenance::DB_STD - For normal DB access, default
533 * Maintenance::DB_ADMIN - For admin DB access
536 public function getDbType() {
541 * Add the default parameters to the scripts
543 protected function addDefaultParams() {
544 # Generic (non script dependant) options:
546 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
547 $this->addOption( 'quiet', 'Whether to suppress non-error output', false, false, 'q' );
548 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
549 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
550 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
553 'Set a specific memory limit for the script, '
554 . '"max" for no limit or "default" to avoid changing it',
558 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
559 "http://en.wikipedia.org. This is sometimes necessary because " .
560 "server name detection may fail in command line scripts.", false, true );
561 $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
562 // This is named --mwdebug, because --debug would conflict in the phpunit.php CLI script.
563 $this->addOption( 'mwdebug', 'Enable built-in MediaWiki development settings', false, true );
565 # Save generic options to display them separately in help
566 $this->mGenericParameters
= $this->mParams
;
568 # Script dependant options:
570 // If we support a DB, show the options
571 if ( $this->getDbType() > 0 ) {
572 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
573 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
574 $this->addOption( 'dbgroupdefault', 'The default DB group to use.', false, true );
577 # Save additional script dependant options to display
578 # Â them separately in help
579 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
586 public function getConfig() {
587 if ( $this->config
=== null ) {
588 $this->config
= MediaWikiServices
::getInstance()->getMainConfig();
591 return $this->config
;
596 * @param Config $config
598 public function setConfig( Config
$config ) {
599 $this->config
= $config;
603 * Indicate that the specified extension must be
604 * loaded before the script can run.
606 * This *must* be called in the constructor.
609 * @param string $name
611 protected function requireExtension( $name ) {
612 $this->requiredExtensions
[] = $name;
616 * Verify that the required extensions are installed
620 public function checkRequiredExtensions() {
621 $registry = ExtensionRegistry
::getInstance();
623 foreach ( $this->requiredExtensions
as $name ) {
624 if ( !$registry->isLoaded( $name ) ) {
630 $joined = implode( ', ', $missing );
631 $msg = "The following extensions are required to be installed "
632 . "for this script to run: $joined. Please enable them and then try again.";
633 $this->fatalError( $msg );
638 * Set triggers like when to try to run deferred updates
641 public function setAgentAndTriggers() {
642 if ( function_exists( 'posix_getpwuid' ) ) {
643 $agent = posix_getpwuid( posix_geteuid() )['name'];
647 $agent .= '@' . wfHostname();
649 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
650 // Add a comment for easy SHOW PROCESSLIST interpretation
651 $lbFactory->setAgentName(
652 mb_strlen( $agent ) > 15 ?
mb_substr( $agent, 0, 15 ) . '...' : $agent
654 self
::setLBFactoryTriggers( $lbFactory, $this->getConfig() );
658 * @param LBFactory $LBFactory
659 * @param Config $config
662 public static function setLBFactoryTriggers( LBFactory
$LBFactory, Config
$config ) {
663 $services = MediaWikiServices
::getInstance();
664 $stats = $services->getStatsdDataFactory();
665 // Hook into period lag checks which often happen in long-running scripts
666 $lbFactory = $services->getDBLoadBalancerFactory();
667 $lbFactory->setWaitForReplicationListener(
669 function () use ( $stats, $config ) {
670 // Check config in case of JobRunner and unit tests
671 if ( $config->get( 'CommandLineMode' ) ) {
672 DeferredUpdates
::tryOpportunisticExecute( 'run' );
674 // Try to periodically flush buffered metrics to avoid OOMs
675 MediaWiki
::emitBufferedStatsdData( $stats, $config );
678 // Check for other windows to run them. A script may read or do a few writes
679 // to the master but mostly be writing to something else, like a file store.
680 $lbFactory->getMainLB()->setTransactionListener(
682 function ( $trigger ) use ( $stats, $config ) {
683 // Check config in case of JobRunner and unit tests
684 if ( $config->get( 'CommandLineMode' ) && $trigger === IDatabase
::TRIGGER_COMMIT
) {
685 DeferredUpdates
::tryOpportunisticExecute( 'run' );
687 // Try to periodically flush buffered metrics to avoid OOMs
688 MediaWiki
::emitBufferedStatsdData( $stats, $config );
694 * Run a child maintenance script. Pass all of the current arguments
696 * @param string $maintClass A name of a child maintenance class
697 * @param string|null $classFile Full path of where the child is
698 * @return Maintenance
700 public function runChild( $maintClass, $classFile = null ) {
701 // Make sure the class is loaded first
702 if ( !class_exists( $maintClass ) ) {
704 require_once $classFile;
706 if ( !class_exists( $maintClass ) ) {
707 $this->error( "Cannot spawn child: $maintClass" );
712 * @var $child Maintenance
714 $child = new $maintClass();
715 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
716 if ( !is_null( $this->mDb
) ) {
717 $child->setDB( $this->mDb
);
724 * Do some sanity checking and basic setup
726 public function setup() {
727 global $IP, $wgCommandLineMode;
729 # Abort if called from a web server
730 # wfIsCLI() is not available yet
731 if ( PHP_SAPI
!== 'cli' && PHP_SAPI
!== 'phpdbg' ) {
732 $this->fatalError( 'This script must be run from the command line' );
735 if ( $IP === null ) {
736 $this->fatalError( "\$IP not set, aborting!\n" .
737 '(Did you forget to call parent::__construct() in your maintenance script?)' );
740 # Make sure we can handle script parameters
741 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
742 $this->fatalError( 'Cannot get command line arguments, register_argc_argv is set to false' );
745 // Send PHP warnings and errors to stderr instead of stdout.
746 // This aids in diagnosing problems, while keeping messages
747 // out of redirected output.
748 if ( ini_get( 'display_errors' ) ) {
749 ini_set( 'display_errors', 'stderr' );
752 $this->loadParamsAndArgs();
754 # Set the memory limit
755 # Note we need to set it again later in cache LocalSettings changed it
756 $this->adjustMemoryLimit();
758 # Set max execution time to 0 (no limit). PHP.net says that
759 # "When running PHP from the command line the default setting is 0."
760 # But sometimes this doesn't seem to be the case.
761 ini_set( 'max_execution_time', 0 );
763 # Define us as being in MediaWiki
764 define( 'MEDIAWIKI', true );
766 $wgCommandLineMode = true;
768 # Turn off output buffering if it's on
769 while ( ob_get_level() > 0 ) {
775 * Normally we disable the memory_limit when running admin scripts.
776 * Some scripts may wish to actually set a limit, however, to avoid
777 * blowing up unexpectedly. We also support a --memory-limit option,
778 * to allow sysadmins to explicitly set one if they'd prefer to override
779 * defaults (or for people using Suhosin which yells at you for trying
780 * to disable the limits)
783 public function memoryLimit() {
784 $limit = $this->getOption( 'memory-limit', 'max' );
785 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
790 * Adjusts PHP's memory limit to better suit our needs, if needed.
792 protected function adjustMemoryLimit() {
793 $limit = $this->memoryLimit();
794 if ( $limit == 'max' ) {
795 $limit = -1; // no memory limit
797 if ( $limit != 'default' ) {
798 ini_set( 'memory_limit', $limit );
803 * Activate the profiler (assuming $wgProfiler is set)
805 protected function activateProfiler() {
806 global $wgProfiler, $wgProfileLimit, $wgTrxProfilerLimits;
808 $output = $this->getOption( 'profiler' );
813 if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
814 $class = $wgProfiler['class'];
815 /** @var Profiler $profiler */
816 $profiler = new $class(
817 [ 'sampling' => 1, 'output' => [ $output ] ]
819 +
[ 'threshold' => $wgProfileLimit ]
821 $profiler->setTemplated( true );
822 Profiler
::replaceStubInstance( $profiler );
825 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
826 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
827 $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__
);
831 * Clear all params and arguments.
833 public function clearParamsAndArgs() {
834 $this->mOptions
= [];
836 $this->mInputLoaded
= false;
840 * Load params and arguments from a given array
841 * of command-line arguments
846 public function loadWithArgv( $argv ) {
849 $this->orderedOptions
= [];
852 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
853 if ( $arg == '--' ) {
854 # End of options, remainder should be considered arguments
855 $arg = next( $argv );
856 while ( $arg !== false ) {
858 $arg = next( $argv );
861 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
863 $option = substr( $arg, 2 );
864 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
865 $param = next( $argv );
866 if ( $param === false ) {
867 $this->error( "\nERROR: $option parameter needs a value after it\n" );
868 $this->maybeHelp( true );
871 $this->setParam( $options, $option, $param );
873 $bits = explode( '=', $option, 2 );
874 $this->setParam( $options, $bits[0], $bits[1] ??
1 );
876 } elseif ( $arg == '-' ) {
877 # Lonely "-", often used to indicate stdin or stdout.
879 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
881 $argLength = strlen( $arg );
882 for ( $p = 1; $p < $argLength; $p++
) {
884 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
885 $option = $this->mShortParamsMap
[$option];
888 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
889 $param = next( $argv );
890 if ( $param === false ) {
891 $this->error( "\nERROR: $option parameter needs a value after it\n" );
892 $this->maybeHelp( true );
894 $this->setParam( $options, $option, $param );
896 $this->setParam( $options, $option, 1 );
904 $this->mOptions
= $options;
905 $this->mArgs
= $args;
906 $this->loadSpecialVars();
907 $this->mInputLoaded
= true;
911 * Helper function used solely by loadParamsAndArgs
912 * to prevent code duplication
914 * This sets the param in the options array based on
915 * whether or not it can be specified multiple times.
918 * @param array $options
919 * @param string $option
920 * @param mixed $value
922 private function setParam( &$options, $option, $value ) {
923 $this->orderedOptions
[] = [ $option, $value ];
925 if ( isset( $this->mParams
[$option] ) ) {
926 $multi = $this->mParams
[$option]['multiOccurrence'];
930 $exists = array_key_exists( $option, $options );
931 if ( $multi && $exists ) {
932 $options[$option][] = $value;
933 } elseif ( $multi ) {
934 $options[$option] = [ $value ];
935 } elseif ( !$exists ) {
936 $options[$option] = $value;
938 $this->error( "\nERROR: $option parameter given twice\n" );
939 $this->maybeHelp( true );
944 * Process command line arguments
945 * $mOptions becomes an array with keys set to the option names
946 * $mArgs becomes a zero-based array containing the non-option arguments
948 * @param string|null $self The name of the script, if any
949 * @param array|null $opts An array of options, in form of key=>value
950 * @param array|null $args An array of command line arguments
952 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
953 # If we were given opts or args, set those and return early
955 $this->mSelf
= $self;
956 $this->mInputLoaded
= true;
959 $this->mOptions
= $opts;
960 $this->mInputLoaded
= true;
963 $this->mArgs
= $args;
964 $this->mInputLoaded
= true;
967 # If we've already loaded input (either by user values or from $argv)
968 # skip on loading it again. The array_shift() will corrupt values if
969 # it's run again and again
970 if ( $this->mInputLoaded
) {
971 $this->loadSpecialVars();
977 $this->mSelf
= $argv[0];
978 $this->loadWithArgv( array_slice( $argv, 1 ) );
982 * Run some validation checks on the params, etc
984 public function validateParamsAndArgs() {
986 # Check to make sure we've got all the required options
987 foreach ( $this->mParams
as $opt => $info ) {
988 if ( $info['require'] && !$this->hasOption( $opt ) ) {
989 $this->error( "Param $opt required!" );
994 foreach ( $this->mArgList
as $k => $info ) {
995 if ( $info['require'] && !$this->hasArg( $k ) ) {
996 $this->error( 'Argument <' . $info['name'] . '> required!' );
1000 if ( !$this->mAllowUnregisteredOptions
) {
1001 # Check for unexpected options
1002 foreach ( $this->mOptions
as $opt => $val ) {
1003 if ( !$this->supportsOption( $opt ) ) {
1004 $this->error( "Unexpected option $opt!" );
1010 $this->maybeHelp( $die );
1014 * Handle the special variables that are global to all scripts
1016 protected function loadSpecialVars() {
1017 if ( $this->hasOption( 'dbuser' ) ) {
1018 $this->mDbUser
= $this->getOption( 'dbuser' );
1020 if ( $this->hasOption( 'dbpass' ) ) {
1021 $this->mDbPass
= $this->getOption( 'dbpass' );
1023 if ( $this->hasOption( 'quiet' ) ) {
1024 $this->mQuiet
= true;
1026 if ( $this->hasOption( 'batch-size' ) ) {
1027 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
1032 * Maybe show the help.
1033 * @param bool $force Whether to force the help to show, default false
1035 protected function maybeHelp( $force = false ) {
1036 if ( !$force && !$this->hasOption( 'help' ) ) {
1040 $screenWidth = 80; // TODO: Calculate this!
1042 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
1044 ksort( $this->mParams
);
1045 $this->mQuiet
= false;
1048 if ( $this->mDescription
) {
1049 $this->output( "\n" . wordwrap( $this->mDescription
, $screenWidth ) . "\n" );
1051 $output = "\nUsage: php " . basename( $this->mSelf
);
1053 // ... append parameters ...
1054 if ( $this->mParams
) {
1055 $output .= " [--" . implode( "|--", array_keys( $this->mParams
) ) . "]";
1058 // ... and append arguments.
1059 if ( $this->mArgList
) {
1061 foreach ( $this->mArgList
as $k => $arg ) {
1062 if ( $arg['require'] ) {
1063 $output .= '<' . $arg['name'] . '>';
1065 $output .= '[' . $arg['name'] . ']';
1067 if ( $k < count( $this->mArgList
) - 1 ) {
1072 $this->output( "$output\n\n" );
1074 # TODO abstract some repetitive code below
1076 // Generic parameters
1077 $this->output( "Generic maintenance parameters:\n" );
1078 foreach ( $this->mGenericParameters
as $par => $info ) {
1079 if ( $info['shortName'] !== false ) {
1080 $par .= " (-{$info['shortName']})";
1083 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1084 "\n$tab$tab" ) . "\n"
1087 $this->output( "\n" );
1089 $scriptDependantParams = $this->mDependantParameters
;
1090 if ( count( $scriptDependantParams ) > 0 ) {
1091 $this->output( "Script dependant parameters:\n" );
1092 // Parameters description
1093 foreach ( $scriptDependantParams as $par => $info ) {
1094 if ( $info['shortName'] !== false ) {
1095 $par .= " (-{$info['shortName']})";
1098 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1099 "\n$tab$tab" ) . "\n"
1102 $this->output( "\n" );
1105 // Script specific parameters not defined on construction by
1106 // Maintenance::addDefaultParams()
1107 $scriptSpecificParams = array_diff_key(
1108 # all script parameters:
1110 # remove the Maintenance default parameters:
1111 $this->mGenericParameters
,
1112 $this->mDependantParameters
1114 if ( count( $scriptSpecificParams ) > 0 ) {
1115 $this->output( "Script specific parameters:\n" );
1116 // Parameters description
1117 foreach ( $scriptSpecificParams as $par => $info ) {
1118 if ( $info['shortName'] !== false ) {
1119 $par .= " (-{$info['shortName']})";
1122 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1123 "\n$tab$tab" ) . "\n"
1126 $this->output( "\n" );
1130 if ( count( $this->mArgList
) > 0 ) {
1131 $this->output( "Arguments:\n" );
1132 // Arguments description
1133 foreach ( $this->mArgList
as $info ) {
1134 $openChar = $info['require'] ?
'<' : '[';
1135 $closeChar = $info['require'] ?
'>' : ']';
1137 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1138 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1141 $this->output( "\n" );
1148 * Handle some last-minute setup here.
1150 public function finalSetup() {
1151 global $wgCommandLineMode, $wgServer, $wgShowExceptionDetails, $wgShowHostnames;
1152 global $wgDBadminuser, $wgDBadminpassword, $wgDBDefaultGroup;
1153 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
1155 # Turn off output buffering again, it might have been turned on in the settings files
1156 if ( ob_get_level() ) {
1160 $wgCommandLineMode = true;
1162 # Override $wgServer
1163 if ( $this->hasOption( 'server' ) ) {
1164 $wgServer = $this->getOption( 'server', $wgServer );
1167 # If these were passed, use them
1168 if ( $this->mDbUser
) {
1169 $wgDBadminuser = $this->mDbUser
;
1171 if ( $this->mDbPass
) {
1172 $wgDBadminpassword = $this->mDbPass
;
1174 if ( $this->hasOption( 'dbgroupdefault' ) ) {
1175 $wgDBDefaultGroup = $this->getOption( 'dbgroupdefault', null );
1177 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1180 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
1181 $wgDBuser = $wgDBadminuser;
1182 $wgDBpassword = $wgDBadminpassword;
1184 if ( $wgDBservers ) {
1186 * @var $wgDBservers array
1188 foreach ( $wgDBservers as $i => $server ) {
1189 $wgDBservers[$i]['user'] = $wgDBuser;
1190 $wgDBservers[$i]['password'] = $wgDBpassword;
1193 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1194 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1195 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1197 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1200 # Apply debug settings
1201 if ( $this->hasOption( 'mwdebug' ) ) {
1202 require __DIR__
. '/../includes/DevelopmentSettings.php';
1205 // Per-script profiling; useful for debugging
1206 $this->activateProfiler();
1208 $this->afterFinalSetup();
1210 $wgShowExceptionDetails = true;
1211 $wgShowHostnames = true;
1213 Wikimedia\
suppressWarnings();
1214 set_time_limit( 0 );
1215 Wikimedia\restoreWarnings
();
1217 $this->adjustMemoryLimit();
1221 * Execute a callback function at the end of initialisation
1223 protected function afterFinalSetup() {
1224 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1225 call_user_func( MW_CMDLINE_CALLBACK
);
1230 * Potentially debug globals. Originally a feature only
1233 public function globals() {
1234 if ( $this->hasOption( 'globals' ) ) {
1235 print_r( $GLOBALS );
1240 * Generic setup for most installs. Returns the location of LocalSettings
1243 public function loadSettings() {
1244 global $wgCommandLineMode, $IP;
1246 if ( isset( $this->mOptions
['conf'] ) ) {
1247 $settingsFile = $this->mOptions
['conf'];
1248 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1249 $settingsFile = MW_CONFIG_FILE
;
1251 $settingsFile = "$IP/LocalSettings.php";
1253 if ( isset( $this->mOptions
['wiki'] ) ) {
1254 $bits = explode( '-', $this->mOptions
['wiki'], 2 );
1255 define( 'MW_DB', $bits[0] );
1256 define( 'MW_PREFIX', $bits[1] ??
'' );
1257 } elseif ( isset( $this->mOptions
['server'] ) ) {
1258 // Provide the option for site admins to detect and configure
1259 // multiple wikis based on server names. This offers --server
1260 // as alternative to --wiki.
1261 // See https://www.mediawiki.org/wiki/Manual:Wiki_family
1262 $_SERVER['SERVER_NAME'] = $this->mOptions
['server'];
1265 if ( !is_readable( $settingsFile ) ) {
1266 $this->fatalError( "A copy of your installation's LocalSettings.php\n" .
1267 "must exist and be readable in the source directory.\n" .
1268 "Use --conf to specify it." );
1270 $wgCommandLineMode = true;
1272 return $settingsFile;
1276 * Support function for cleaning up redundant text records
1277 * @param bool $delete Whether or not to actually delete the records
1278 * @author Rob Church <robchur@gmail.com>
1280 public function purgeRedundantText( $delete = true ) {
1281 global $wgMultiContentRevisionSchemaMigrationStage;
1283 # Data should come off the master, wrapped in a transaction
1284 $dbw = $this->getDB( DB_MASTER
);
1285 $this->beginTransaction( $dbw, __METHOD__
);
1287 if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_READ_OLD
) {
1288 # Get "active" text records from the revisions table
1290 $this->output( 'Searching for active text records in revisions table...' );
1291 $res = $dbw->select( 'revision', 'rev_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1292 foreach ( $res as $row ) {
1293 $cur[] = $row->rev_text_id
;
1295 $this->output( "done.\n" );
1297 # Get "active" text records from the archive table
1298 $this->output( 'Searching for active text records in archive table...' );
1299 $res = $dbw->select( 'archive', 'ar_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1300 foreach ( $res as $row ) {
1301 # old pre-MW 1.5 records can have null ar_text_id's.
1302 if ( $row->ar_text_id
!== null ) {
1303 $cur[] = $row->ar_text_id
;
1306 $this->output( "done.\n" );
1308 # Get "active" text records via the content table
1310 $this->output( 'Searching for active text records via contents table...' );
1311 $res = $dbw->select( 'content', 'content_address', [], __METHOD__
, [ 'DISTINCT' ] );
1312 $blobStore = MediaWikiServices
::getInstance()->getBlobStore();
1313 foreach ( $res as $row ) {
1314 $textId = $blobStore->getTextIdFromAddress( $row->content_address
);
1319 $this->output( "done.\n" );
1321 $this->output( "done.\n" );
1323 # Get the IDs of all text records not in these sets
1324 $this->output( 'Searching for inactive text records...' );
1325 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1326 $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__
, [ 'DISTINCT' ] );
1328 foreach ( $res as $row ) {
1329 $old[] = $row->old_id
;
1331 $this->output( "done.\n" );
1333 # Inform the user of what we're going to do
1334 $count = count( $old );
1335 $this->output( "$count inactive items found.\n" );
1337 # Delete as appropriate
1338 if ( $delete && $count ) {
1339 $this->output( 'Deleting...' );
1340 $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__
);
1341 $this->output( "done.\n" );
1344 $this->commitTransaction( $dbw, __METHOD__
);
1348 * Get the maintenance directory.
1351 protected function getDir() {
1356 * Returns a database to be used by current maintenance script. It can be set by setDB().
1357 * If not set, wfGetDB() will be used.
1358 * This function has the same parameters as wfGetDB()
1360 * @param int $db DB index (DB_REPLICA/DB_MASTER)
1361 * @param string|string[] $groups default: empty array
1362 * @param string|bool $wiki default: current wiki
1363 * @return IMaintainableDatabase
1365 protected function getDB( $db, $groups = [], $wiki = false ) {
1366 if ( $this->mDb
=== null ) {
1367 return wfGetDB( $db, $groups, $wiki );
1373 * Sets database object to be returned by getDB().
1375 * @param IDatabase $db
1377 public function setDB( IDatabase
$db ) {
1382 * Begin a transcation on a DB
1384 * This method makes it clear that begin() is called from a maintenance script,
1385 * which has outermost scope. This is safe, unlike $dbw->begin() called in other places.
1387 * @param IDatabase $dbw
1388 * @param string $fname Caller name
1391 protected function beginTransaction( IDatabase
$dbw, $fname ) {
1392 $dbw->begin( $fname );
1396 * Commit the transcation on a DB handle and wait for replica DBs to catch up
1398 * This method makes it clear that commit() is called from a maintenance script,
1399 * which has outermost scope. This is safe, unlike $dbw->commit() called in other places.
1401 * @param IDatabase $dbw
1402 * @param string $fname Caller name
1403 * @return bool Whether the replica DB wait succeeded
1406 protected function commitTransaction( IDatabase
$dbw, $fname ) {
1407 $dbw->commit( $fname );
1408 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
1409 $waitSucceeded = $lbFactory->waitForReplication(
1410 [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait
]
1412 $this->lastReplicationWait
= microtime( true );
1413 return $waitSucceeded;
1417 * Rollback the transcation on a DB handle
1419 * This method makes it clear that rollback() is called from a maintenance script,
1420 * which has outermost scope. This is safe, unlike $dbw->rollback() called in other places.
1422 * @param IDatabase $dbw
1423 * @param string $fname Caller name
1426 protected function rollbackTransaction( IDatabase
$dbw, $fname ) {
1427 $dbw->rollback( $fname );
1431 * Lock the search index
1432 * @param IMaintainableDatabase &$db
1434 private function lockSearchindex( $db ) {
1435 $write = [ 'searchindex' ];
1445 $db->lockTables( $read, $write, __CLASS__
. '-searchIndexLock' );
1450 * @param IMaintainableDatabase &$db
1452 private function unlockSearchindex( $db ) {
1453 $db->unlockTables( __CLASS__
. '-searchIndexLock' );
1457 * Unlock and lock again
1458 * Since the lock is low-priority, queued reads will be able to complete
1459 * @param IMaintainableDatabase &$db
1461 private function relockSearchindex( $db ) {
1462 $this->unlockSearchindex( $db );
1463 $this->lockSearchindex( $db );
1467 * Perform a search index update with locking
1468 * @param int $maxLockTime The maximum time to keep the search index locked.
1469 * @param string $callback The function that will update the function.
1470 * @param IMaintainableDatabase $dbw
1471 * @param array $results
1473 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1477 if ( $maxLockTime ) {
1478 $this->output( " --- Waiting for lock ---" );
1479 $this->lockSearchindex( $dbw );
1481 $this->output( "\n" );
1484 # Loop through the results and do a search update
1485 foreach ( $results as $row ) {
1486 # Allow reads to be processed
1487 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1488 $this->output( " --- Relocking ---" );
1489 $this->relockSearchindex( $dbw );
1491 $this->output( "\n" );
1493 call_user_func( $callback, $dbw, $row );
1496 # Unlock searchindex
1497 if ( $maxLockTime ) {
1498 $this->output( " --- Unlocking --" );
1499 $this->unlockSearchindex( $dbw );
1500 $this->output( "\n" );
1505 * Update the searchindex table for a given pageid
1506 * @param IDatabase $dbw A database write handle
1507 * @param int $pageId The page ID to update.
1508 * @return null|string
1510 public function updateSearchIndexForPage( $dbw, $pageId ) {
1511 // Get current revision
1512 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1515 $titleObj = $rev->getTitle();
1516 $title = $titleObj->getPrefixedDBkey();
1517 $this->output( "$title..." );
1518 # Update searchindex
1519 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1521 $this->output( "\n" );
1528 * Count down from $seconds to zero on the terminal, with a one-second pause
1529 * between showing each number. If the maintenance script is in quiet mode,
1530 * this function does nothing.
1534 * @codeCoverageIgnore
1535 * @param int $seconds
1537 protected function countDown( $seconds ) {
1538 if ( $this->isQuiet() ) {
1541 for ( $i = $seconds; $i >= 0; $i-- ) {
1542 if ( $i != $seconds ) {
1543 $this->output( str_repeat( "\x08", strlen( $i +
1 ) ) );
1545 $this->output( $i );
1550 $this->output( "\n" );
1554 * Wrapper for posix_isatty()
1555 * We default as considering stdin a tty (for nice readline methods)
1556 * but treating stout as not a tty to avoid color codes
1558 * @param mixed $fd File descriptor
1561 public static function posix_isatty( $fd ) {
1562 if ( !function_exists( 'posix_isatty' ) ) {
1565 return posix_isatty( $fd );
1570 * Prompt the console for input
1571 * @param string $prompt What to begin the line with, like '> '
1572 * @return string Response
1574 public static function readconsole( $prompt = '> ' ) {
1575 static $isatty = null;
1576 if ( is_null( $isatty ) ) {
1577 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1580 if ( $isatty && function_exists( 'readline' ) ) {
1581 return readline( $prompt );
1584 $st = self
::readlineEmulation( $prompt );
1586 if ( feof( STDIN
) ) {
1589 $st = fgets( STDIN
, 1024 );
1592 if ( $st === false ) {
1595 $resp = trim( $st );
1602 * Emulate readline()
1603 * @param string $prompt What to begin the line with, like '> '
1606 private static function readlineEmulation( $prompt ) {
1607 $bash = ExecutableFinder
::findInDefaultPaths( 'bash' );
1608 if ( !wfIsWindows() && $bash ) {
1610 $encPrompt = wfEscapeShellArg( $prompt );
1611 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1612 $encCommand = wfEscapeShellArg( $command );
1613 $line = wfShellExec( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1615 if ( $retval == 0 ) {
1617 } elseif ( $retval == 127 ) {
1618 // Couldn't execute bash even though we thought we saw it.
1619 // Shell probably spit out an error message, sorry :(
1620 // Fall through to fgets()...
1627 // Fallback... we'll have no editing controls, EWWW
1628 if ( feof( STDIN
) ) {
1633 return fgets( STDIN
, 1024 );
1637 * Get the terminal size as a two-element array where the first element
1638 * is the width (number of columns) and the second element is the height
1643 public static function getTermSize() {
1644 $default = [ 80, 50 ];
1645 if ( wfIsWindows() ) {
1648 if ( Shell
::isDisabled() ) {
1651 // It's possible to get the screen size with VT-100 terminal escapes,
1652 // but reading the responses is not possible without setting raw mode
1653 // (unless you want to require the user to press enter), and that
1654 // requires an ioctl(), which we can't do. So we have to shell out to
1655 // something that can do the relevant syscalls. There are a few
1656 // options. Linux and Mac OS X both have "stty size" which does the
1658 $result = Shell
::command( 'stty', 'size' )
1660 if ( $result->getExitCode() !== 0 ) {
1663 if ( !preg_match( '/^(\d+) (\d+)$/', $result->getStdout(), $m ) ) {
1666 return [ intval( $m[2] ), intval( $m[1] ) ];
1670 * Call this to set up the autoloader to allow classes to be used from the
1673 public static function requireTestsAutoloader() {
1674 require_once __DIR__
. '/../tests/common/TestsAutoLoader.php';
1679 * Fake maintenance wrapper, mostly used for the web installer/updater
1681 class FakeMaintenance
extends Maintenance
{
1682 protected $mSelf = "FakeMaintenanceScript";
1684 public function execute() {
1689 * Class for scripts that perform database maintenance and want to log the
1690 * update in `updatelog` so we can later skip it
1692 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1693 public function __construct() {
1694 parent
::__construct();
1695 $this->addOption( 'force', 'Run the update even if it was completed already' );
1696 $this->setBatchSize( 200 );
1699 public function execute() {
1700 $db = $this->getDB( DB_MASTER
);
1701 $key = $this->getUpdateKey();
1703 if ( !$this->hasOption( 'force' )
1704 && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__
)
1706 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1711 if ( !$this->doDBUpdates() ) {
1715 $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__
, 'IGNORE' );
1721 * Message to show that the update was done already and was just skipped
1724 protected function updateSkippedMessage() {
1725 $key = $this->getUpdateKey();
1727 return "Update '{$key}' already logged as completed.";
1731 * Do the actual work. All child classes will need to implement this.
1732 * Return true to log the update as done or false (usually on failure).
1735 abstract protected function doDBUpdates();
1738 * Get the update key name to go in the update log table
1741 abstract protected function getUpdateKey();